package weixin.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.fasterxml.jackson.databind.ObjectMapper;

import weixin.service.WechatService;

public class BaseUtils
{
    private static Logger logger = Logger.getLogger(BaseUtils.class);
    @SuppressWarnings("unused")
	private static ObjectMapper objectMapper = new ObjectMapper();
    
    private static WechatService wechatService;
    
	public static  String getAccess_token(){
		return wechatService.getAccess_token();
	}
    
    public static String getApi_ticket()
    {
		return wechatService.getApi_ticket();
    }
   
    
    /**
     *@note: 获取js-sdk的配置	
     *@date: 2017年4月22日 下午11:05:44
     *@param url
     *@return
     */
    public static Map<String, String> getConfig(String url)
    {
		String jsapi_ticket = getApi_ticket();
        Map<String, String> ret = new HashMap<String, String>();
        String nonceStr = UUID.randomUUID().toString().replaceAll("-", "");
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String string1;
        String signature = "";
        
        // 注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url=" + url;
        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            
            Formatter formatter = new Formatter();
            for (byte b : crypt.digest())
            {
                formatter.format("%02x", b);
            }
            signature = formatter.toString();
            formatter.close();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        
        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonceStr);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("string1",string1);
        return ret;
    }
    
    
    /**
     *@note: userid兑换openid	
     *@date: 2017年7月4日 下午11:21:06
     *@param access_token
     *@param openid
     *@return
     */
    public static String openidToUserid(String access_token, String openid)
    {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_userid?access_token=" + access_token;
        String data = "{\"openid\": \"" + openid + "\"}";
        String result = RequestUtils.doPost(url, data);
        return result;
    }
    
    /**
     * 2016年7月12日 下午2:06:42
     * 
     * @param access_token
     * @return
     * @note:获取所有微信服务器ip
     */
    public static List<String> getIp_list(String access_token)
    {
        String url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" + access_token;
        String result = RequestUtils.doGet(url);
        result = result.replaceAll("\"", "").replaceAll("\\{", "").replaceAll("\\}", "").split(":")[1].replace("[", "")
            .replace("]", "");
        String[] list = result.split(",");
        return Arrays.asList(list);
    }
    
    @SuppressWarnings("finally")
    public static Map<String, String> xmlToMap(String xml)
    {
        Document document = null;
        Map<String, String> resultMap = new HashMap<>();
        try
        {
            document = DocumentHelper.parseText(xml);
            Element root = document.getRootElement();
            for (Iterator<?> it = root.elementIterator(); it.hasNext();)
            {
                Element element = (Element)it.next();
                resultMap.put(element.getName(), element.getText());
            }
        }
        catch (DocumentException e)
        {
            logger.error("xmlToMap:" + e.getMessage());
        }
        finally
        {
            return resultMap;
        }
    }
    
	public static void setWechatService(WechatService wechatService) {
    	if(BaseUtils.wechatService==null){
    		BaseUtils.wechatService = wechatService;
    	}
	}
}
